#!/bin/sh

# Reconnect automatically NetworkManager's VPN connections
# Copyright (C) 2012, 2013 Bruno Carnazzi <bcarnazzi@gmail.com>
# Released under the terms of the New BSD License.

PROGRAM=nm-dispatcher-vpnguard
VERSION=0.5.1

DISABLE_FILE=/var/run/vpnguard.disable
CONFIG=/etc/${PROGRAM}.conf
source ${CONFIG}

INTERFACE=$1
STATUS=$2

warn() {
	[ ${DEBUG} -eq 1 ] && echo "$1" | logger -p user.warn -t ${PROGRAM}
}

err() {
	echo "$1" | logger -p user.err -t ${PROGRAM}
}

vpn_up() {
	# ${PARENT_INTERFACE} MUST be up before bringing up VPN
	if ifconfig ${PARENT_INTERFACE} | grep RUNNING ; then
		warn "Bringing up VPN connection: ${VPN_NAME}"
		nmcli con up id "${VPN_NAME}"
	fi
}

vpn_down() {
	warn "Bringing down VPN connection: ${VPN_NAME}"
	nmcli con down ip "${VPN_NAME}"
}



warn "Status of ${INTERFACE} has changed to ${STATUS}"
if [ -f "${DISABLE_FILE}" ] ; then
	warn "Warning: vpnguard is disabled."
	exit 0
fi

if [ ${INTERFACE} = ${VPN_INTERFACE} ] ; then
	if [ ${STATUS} = "vpn-up" ] ; then
		if [ "${SUSPEND_PROCS}" ] ; then
			warn "Resuming processes: ${SUSPEND_PROCS}"
			killall -SIGCONT ${SUSPEND_PROCS}
		fi
	elif [ ${STATUS} = "vpn-down" ] ; then
		if [ "${SUSPEND_PROCS}" ] ; then
			warn "Suspending processes: ${SUSPEND_PROCS}"
			killall -SIGSTOP ${SUSPEND_PROCS}
		fi
		vpn_up
	fi
elif [ ${INTERFACE} = ${PARENT_INTERFACE} ] ; then
	if [ ${STATUS} = "down" ] ; then
		if nmcli con status id "${VPN_NAME}" ; then
			vpn_down
		fi
	elif [ ${STATUS} = "up" ] ; then
		vpn_up
	fi
fi
